<?php

class Mageex_Robot_Helper_Rss extends Mage_Core_Helper_Abstract
{
	public function rssPost($keyword = "", $num, $start, $url)
	{
		$kw 	= $keyword;
		$url 	= trim($url);
		$url 	= urldecode($url);
		$start 	= 0;
		$found 	= 0;
		if(function_exists('curl_init')){
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Konqueror/4.0; Microsoft Windows) KHTML/4.0.80 (like Gecko)");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);
			$response = curl_exec($ch);
			if (!$response) {
				$return["error"]["reason"] = "cURL Error";
				$return["error"]["message"] = Mage::helper('robot')->__("cURL Error Number ").curl_errno($ch).": ".curl_error($ch);	
				return $return;
			}
			curl_close($ch);
		}else{
			$response = @file_get_contents($url);
			if (!$response) {
				$return["error"]["reason"] = "cURL Error";
				$return["error"]["message"] = Mage::helper('robot')->__("cURL is not installed on this server!");	
				return $return;		
			}
		}
		$rss = @simplexml_load_string($response);
		
		if(!$rss){
			$rss = @simplexml_load_file($url);
		}
		if (empty($rss)) {
			$return["error"]["reason"] = "RSS Error";
			$return["error"]["message"] = Mage::helper('robot')->__("RSS Feed could not be loaded or is empty!");	
			return $return;		
		}
		$allabort = 0;	
		$abort = 0;
		$posts = array();
		if(isset($rss->entry)){
			$feed 	= $rss->entry;
			$ffr	= "blogger";
		}elseif(isset($rss->channel->item)){
			$feed 	= $rss->channel->item;
		}else if(isset($rss->item)){
			$feed	= $rss->item;
		}else{
			$feed	= 'stop';
		}
		if($ffr == 'blogger'){
			$ctitle = $rss->title;
		}else{
			$ctitle = $rss->channel->title;
			$clink = $rss->channel->link;
			$cdesc = $rss->channel->description;	
		}
		
		if($feed == 'stop'){
			$return["error"]["reason"] = "Invalid Feed";
			$return["error"]["message"] = Mage::helper('robot')->__("Invalid Feed");	
			return $return;
		}else{
			foreach($feed as $item){
				$title = $item->title;
				$title = preg_replace('/[\r\n\s]+/xms', ' ', trim($title));
				$title = strip_tags($title);
				
				$guid = $item->guid;			
				$gattr = $guid->attributes();			
				if($gattr['isPermaLink'] != "false" && !empty($guid)) {$unguid = $guid;} else {$unguid = "";}
				
				if($ffr == "blogger") {
					
					$link = $item->link;
					$descr = $item->summary;
					$fullcontent = $item->content; 
					$date = $item->published;
					
					foreach ($item->link as $link) {
						$attr = $link->attributes();
						if($link['rel'] == "replies" && $link['type'] == "application/atom+xml") {$commentRss = $link['href'];}
						if($link['rel'] == "alternate") {$sourcelink = $link['href']; }								
					}							
			
				} else {
					$_fullcontent = $item->content;
					$sourcelink = $item->link;						
					$descr 	= $item->description;
					$date 	= $item->pubDate;	

					$dc  	= $item->children("http://purl.org/dc/elements/1.1/");
					$creator = (string) $dc->creator;
					
					$ccc = $item->children("http://purl.org/rss/1.0/modules/content/");
					$fullcontent = (string)trim($ccc->encoded);
					
					if($kw != "" && Mage::helper('robot/config')->getEnableRss()) {
						$kw = str_replace('"', '', $kw);
						
						$kws = explode(" AND ", $kw);
						foreach($kws as $kwx) {
							$kw2 = " ".$kwx." ";
							$c1 = stripos($fullcontent, $kw2);
							$c2 = stripos($descr, $kw2);
							$c3 = stripos($title, $kw2);
							if($c1 != false || $c2 != false || $c3 != false) {
								// keyword was found 
								$abort = 0;
							} else {
								// keyword was not found 					
								$abort = 1;
								$allabort = 1;
							}						
						}
					}
					
					$wfw = $item->children("http://wellformedweb.org/CommentAPI/");
					$commentRss = $wfw->commentRss;	
					
					$enclosure = $item->enclosure["url"];
					
					$media = $item->children('http://search.yahoo.com/mrss/');
					if($media->player) {
						$attrs = $media->player->attributes();
						$mediaplayer = $attrs['url']; 					  
					}
					if($media->content) {							
						$attrs 			= $media->content->attributes();
						$mediacontent 	= $attrs['url']; 
						$mediatype 		= $attrs['type']; 
						$mediaheight 	= $attrs['height']; 
						$mediawidth 	= $attrs['width'];  
						$video ='
							<object width="'.$mediawidth.'" height="'.$mediaheight.'">
							<param name="movie" value="'.$mediacontent.'"></param>
							<embed src="'.$mediacontent.'" type="'.$mediatype.'" width="'.$mediawidth.'" height="'.$mediaheight.'"></embed>
							</object>';		
					}
					if($media->thumbnail) {								  
						$attrs = $media->thumbnail[0]->attributes();
						$mediathumbnail = $attrs['url']; 
					}
								
				}
				if(!empty($unguid)) {$uid = $unguid;} else {$uid = $sourcelink;}	
				// && !wpr_check_unique($uid) check unique
				if($abort != 1 && $allabort != 1) {
					$source = '<a rel="nofollow" href="'.$sourcelink.'">'.$ctitle.'</a>';						
					if($fullcontent != "" && $options['wpr_rss_content']=='full') {$content = $fullcontent;} else {$content = $descr;}
					if ($options['wpr_rss_striplinks']=='yes') {$content = wpr_strip_selected_tags($content, array('a','iframe','script'));}
					
					$post = "{content} {source}";	
					//$post = wpr_random_tags($post);
					$content = str_replace("$", "$ ", $content); 
					$post = str_replace("{content}", $content, $post);			
					$post = str_replace("{source}", $source, $post);	
					$post = str_replace("{author}", $creator, $post);
					$noqkeyword = str_replace('"', '', $keyword);
					$post = str_replace("{keyword}", $noqkeyword, $post);
					$post = str_replace("{Keyword}", ucwords($noqkeyword), $post);			
					$post = str_replace("{url}", $sourcelink, $post);	
					$post = str_replace("{title}", $title, $post);	
					$post = str_replace("{mediacontent}", $video, $post);
					$post = str_replace("{mediathumbnail}", $mediathumbnail, $post);							
					$post = str_replace("{enclosure}", $enclosure, $post);					
					
					if(!empty($mediathumbnail)) {$customfield = $mediathumbnail;} elseif(!empty($enclosure)) {$customfield = $enclosure;} else {$customfield = "";}	
						
					$customfield2 = array();
					$customfield2["rsstitle"] = $title;
					$customfield2["rssmediacontent"] = $video;
					$customfield2["rssenclosure"] = $enclosure;
					$customfield2["rsssource"] = $source;
					$customfield2["rssimage"] = $customfield;						
					$customfield2["content_custom"] = $post;	
					$posts[$found]["unique"] 		= $uid;
					$posts[$found]["title"] 		= $title;
					$posts[$found]["description"] 	= $descr;
					$posts[$found]["full_content"]	= $_fullcontent;	
					
					$posts[$found]["customfield"] 	= $customfield2;
					
					$found++;
					
				}
				
				if($found==$num){
					break;
				}
			}
		}
		if($found > 0) {
			return $posts;		
		} elseif($abort == 1) {
			// error: no posts found for keywords
			$posts["error"]["reason"] = "No content";
			$posts["error"]["message"] = Mage::helper('robot')->__("No post found in RSS feed for keyword $kw");	
			return $posts;					
		} elseif($found == 0) {
			// error: no posts found
			$posts["error"]["reason"] = "No content";
			$posts["error"]["message"] = Mage::helper('robot')->__("No unposted RSS items found!","wprobot");	
			return $posts;	
		} elseif(empty($posts)) {
			// error: no posts found
			$posts["error"]["reason"] = "No content";
			$posts["error"]["message"] = Mage::helper('robot')->__("No items found in this feed!");	
			return $posts;		
		} else {
			// error: no posts found
			$posts["error"]["reason"] = "No content";
			$posts["error"]["message"] = Mage::helper('robot')->__("No items found in this feed!");	
			return $posts;			
		}
	}
}